"""
Case Type   : 逻辑复制
Case Name   : 使用JDBC创建名称中含有符号的逻辑复制槽
Create At   : 2021/01/14
Owner       : opentestcase015
Description :
    1.设置wal_level = logical
    2.创建名称中含有符号的逻辑复制槽
    3.清理环境
Expect      :
    1.成功
    2.合理报错
    3.成功
History     :modified by zopentestcase005,2022.09.13，研发代码变更，含有>符号的逻辑复制槽,
             报错提示为含危险字符
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class LogicalReplication09(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.comsh = CommonSH('dbuser')
        self.constant = Constant()
        self.common = Common()
        self.expect = 'ERROR:  inputString "slot>1" contains ' \
                      'dangerous character'
        self.default_value = self.common.show_param('wal_level')

    def test_logical_replication(self):
        text = '---step1:设置wal_level = logical;expect:成功---'
        self.log.info(text)
        guc_cmd = self.comsh.execute_gsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           'wal_level=logical')
        self.log.info(guc_cmd)
        self.comsh.restart_db_cluster()
        status = self.comsh.get_db_cluster_status()
        self.assertTrue("Normal" in status or 'Degraded' in status,
                        '执行失败' + text)
        sql_cmd = self.comsh.execut_db_sql('show wal_level;')
        self.log.info(sql_cmd)
        self.new_value = sql_cmd.splitlines()[-2].strip()
        self.assertIn('logical', self.new_value, '执行失败' + text)

        text = '--step2:创建名称中含有符号的逻辑复制槽;expect:合理报错--'
        self.log.info(text)
        sql_cmd = self.comsh.execut_db_sql(
            "select * from pg_create_logical_replication_slot"
            "('slot>1', 'mppdb_decoding');")
        self.log.info(sql_cmd)
        self.assertIn(self.expect, sql_cmd, '执行失败' + text)

    def tearDown(self):
        text = '---step3:清理环境;expect:成功---'
        self.log.info(text)
        guc_cmd = self.comsh.execute_gsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           f"wal_level={self.default_value}")
        self.log.info(guc_cmd)
        self.comsh.restart_db_cluster()
        status = self.comsh.get_db_cluster_status()
        self.assertTrue("Normal" in status or 'Degraded' in status,
                        '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
